﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;

namespace BGShell.Components
{
    public class DataTipItem : MarshalByRefObject, IDisposable
    {
        private List<DataTipItem> _items;
        private ReadOnlyCollection<DataTipItem> _itemCollection;

        public DataTipItem()
        {
        }

        public DataTipItem(string value)
        {
            Value = value;
        }

        public DataTipItem(string name, object value)
        {
            Name = name;
            Value = value;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public virtual void PaintIcon(Graphics graphics, Rectangle rect)
        {
        }

        public virtual string Name
        {
            get;
            set;
        }

        public virtual object Value
        {
            get;
            set;
        }

        public virtual string ValueAsString
        {
            get
            {
                if (Value == null)
                {
                    return NullString;
                }

                if (Value is Enum ||
                    Value.GetType().IsPrimitive)
                {
                    return Value.ToString();
                }

                if (Value is string)
                {
                    return '"' + (string)(Value) + '"';
                }

                return '{' + Value.ToString() + '}';
            }
        }
        
        public virtual bool HasIcon
        {
            get { return false; }
        }

        public ICollection<DataTipItem> Subitems
        {
            get 
            {
                if (_itemCollection == null)
                {
                    _items = new List<DataTipItem>();
                    _itemCollection = _items.AsReadOnly();

                    OnCreateSubitems();
                }

                return _itemCollection;
            }
        }

        protected virtual void OnCreateSubitems()
        {
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_items != null)
            {
                foreach (var item in _items)
                {
                    item.Dispose();
                }
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "But I WANT Sort(), AddRange(), et cetera!")]
        protected List<DataTipItem> InnerList
        {
            get { return _items; }
        }

        internal int Index
        {
            get;
            set;
        }

        private const string NullString = "null";
    }
}
